package com.sh.controller;

import com.sh.common.BaseResult;
import com.sh.common.exception.BizException;
import com.sh.pojo.bo.DownloadObjectsBO;
import com.sh.pojo.bo.GetObjectsURLBO;
import com.sh.pojo.bo.SearchObjectBO;
import com.sh.service.store.IOSService;
import com.sh.service.user.IUserResourceService;
import com.sh.utils.PathUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.simpleframework.xml.core.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 * 资源对象-读（校验权限）
 */
@Slf4j
@RestController
@RequestMapping("/user/resource/read")
public class UserReadResourceController {
    @Autowired
    private IUserResourceService userResourceService;
    @Autowired
    private IOSService ossService;

    /**
     * 检索对象
     */
    @PostMapping("/object/list")
    public BaseResult searchObject(@Validate @RequestBody SearchObjectBO bo) throws BizException {
        return BaseResult.success(userResourceService.searchObjects(bo));
    }


    /**
     * 下载、复制URL
     */
    @GetMapping("/signUrl")
    public BaseResult signUrl(@RequestParam(value = "bucket", required = false) String bucket,
                              @RequestParam(value = "path",required = false) @Pattern(regexp = ".*/$", message = "路径需要以'/'结束") String path, @RequestParam("objectName") String objectName,
                              @RequestParam(value = "expires", required = false) Integer expires) {
        String objectKey = null;
        if (StringUtils.isEmpty(path)) {
            objectKey = objectName;
        } else {
            objectKey = path + objectName;
        }
        return BaseResult.success(ossService.signUrl(bucket, objectKey, expires));
    }

    /**
     * 批量下载、复制URL
     */
    @PostMapping("/signUrls")
    public BaseResult signUrl(@Validate @RequestBody GetObjectsURLBO bo) throws BizException {
        return BaseResult.success(userResourceService.downloadObjects(bo.getBucket(),bo.getObjectPath(),bo.getExpire(),bo.getLocalPath()));
    }

    @PostMapping("/objects/download")
    public ResponseEntity<byte[]> download(@Validate @RequestBody DownloadObjectsBO bo) {
        try {
            ByteArrayOutputStream resource=userResourceService.downloadAndZipFiles(bo.getBucket(), bo.getObjectPath());
            if (resource == null) {
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
            byte[] zipBytes = resource.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String zipFileName=PathUtil.getPathNotEndWithSeparator(PathUtil.findLongestCommonPath(bo.getObjectPath()));
            headers.setContentDispositionFormData("attachment", zipFileName+".zip");

            return new ResponseEntity<>(zipBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            log.error("下载文件失败:{}", e);
        }
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
